#include "update.h"
#include "http_client.h"
#include "../core/cJSON.h"
#include "../core/dbg.h"
#include "../user_types.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SERVER_ADDR      "192.168.2.166"
#define SERVER_PORT      11086

uint32_t conversion_ver(const char *ver) 
{
    uint32_t nVer = 0x00;
    int a,b,c,d;
    if (sscanf(ver, "%d.%d.%d.%d", &a, &b, &c, &d) == 4){
        nVer = VERSION_CHECK(a, b, c, d);
    }

    return nVer;
}

int app_version_check(const char *app, const ui32 _appVer) 
{
    char http_url[128];
    sprintf(http_url, "http://%s:%d/cv/%s", SERVER_ADDR, SERVER_PORT & 0xffff, app);
    dbg_msg("http_url: %s", http_url);

    if (http_get(http_url) >= 0) {
        char buffer[256];
        get_reply_text(buffer);
        dbg_msg("check version:\n\t%s\n", buffer);
        cJSON *root = cJSON_Parse(buffer);
        if(root == NULL) {      
            dbg_err("parse JSON failed!");  
            return -1;
        }

        cJSON *code = cJSON_GetObjectItem(root, "code");
        if (NULL != code) {
             if (0 != code->valueint) {
                dbg_err("response code[%d] error!", code->valueint);
                return -1;
            }
        }

        cJSON *strVerInfo = cJSON_GetObjectItem(root, "verInfo");
        if (NULL != strVerInfo) {
            dbg_msg("Version info: %s", strVerInfo->valuestring);
        }
    
        cJSON *strVer = cJSON_GetObjectItem(root, "verNum");
        if (NULL != strVer) {
            ui32 appVer = conversion_ver(strVer->valuestring);
            dbg_msg("server version: 0x%08x --> 0x%08x", appVer, _appVer);
            if (appVer > _appVer) {
                dbg_msg("find new app version: %s", strVer->valuestring);
                return 1;
            }
            else {
                dbg_msg("Currently it is the latest version[%s]", strVer->valuestring);
            }
        }
        else {
            dbg_err("get verNum failed!");
            return -1;
        }
    }

    return 0;
}

int app_version_update(const char *app)
{
    char http_url[128];
    sprintf(http_url, "http://%s:%d/up/%s", SERVER_ADDR, SERVER_PORT & 0xffff, app);
    dbg_msg("http_url: %s", http_url);

    if (http_get(http_url) < 0) {
        dbg_err("download [%s] failed!~", http_url);
        return -1;
    }

    return 0;
}
